import { reactive } from 'vue'
import { LSUtil } from 'tools-vue3'
import System from '~/utils/System'
import { getTabelTree } from '~/views/auth/util/tree'

/**
 * 系统参数
 */
const SSys = reactive({
    auth: {
        list: ['/api/system/list', '/api/system/detail'] as string[],
        isPass: (auth: string) => {
            return SSys.auth.list.includes(auth)
        }
    },

    /**
     * 布局对象
     */
    layout: {
        /**
         * 菜单收缩
         */
        collapse: false
    },
    menuListSource: [] as Menu[],
    menuList: [] as Menu[],
    setMenuList: (menuList: Menu[], menuListSource: Menu[]) => {
        SSys.menuList = menuList
        SSys.menuListSource = menuListSource
        LSUtil.set('menuListSource', JSON.stringify(SSys.menuListSource))
    },
    getMenuList: async (): Promise<Menu[]> => {
        let menuListSource = LSUtil.get('menuListSource')
        try {
            if (!StrUtil.isNull(menuListSource)) menuListSource = JSON.parse(menuListSource)
            if (StrUtil.isNull(menuListSource)) {
                System.router.push('/login')
                return []
            }
            let tree = [getTabelTree(0, menuListSource)]
            SSys.setMenuList(tree[0].children, menuListSource)
            return SSys.menuList
        } catch (error) {
            System.router.push('/login')
        }
        return SSys.menuList
    },

    apiList: [] as string[],
    setApiList: (apiList: string[]) => {
        SSys.apiList = apiList
        LSUtil.set('apiList', JSON.stringify(SSys.apiList))
    },
    getApiList: async (): Promise<string[]> => {
        let apiList = LSUtil.get('apiList')
        try {
            if (!StrUtil.isNull(apiList)) apiList = JSON.parse(apiList)
            if (StrUtil.isNull(apiList)) {
                System.router.push('/login')
                return []
            }
            SSys.setApiList(apiList)
            return SSys.apiList
        } catch (error) {
            System.router.push('/login')
        }
        return SSys.apiList
    }
})

export default SSys

export type Menu = MenuItem & {
    children: Menu[]
}

type MenuItem = {
    id: string
    parentId: string
    createTime: number
    updateTime: number
    title: string
    url: string
    sort: number
    type: number
    icon: string
    iconName: string
    iconFill: string[]
    nav: boolean
    desc: string
}
